import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
import path from 'path';
import type {
  FileTransferProgress,
  FileTransferRequest,
  ScriptExecutionRequest,
  DeviceConnectionEvent,
  DeviceDisconnectionEvent,
  WebSocketServerEvent,
  ScriptResult
} from '../renderer/types';

// 直接导入adbTest的内容
const adbPath = 'D:\\software\\android_sdk\\platform-tools\\adb.exe';

async function scanDevices() {
  const { execFile } = require('child_process');
  const util = require('util');
  const execFileAsync = util.promisify(execFile);

  try {
    const { stdout } = await execFileAsync(adbPath, ['devices', '-l']);
    console.log('ADB输出:', stdout);
    
    const lines = stdout.split('\n').slice(1); // 跳过第一行的 "List of devices attached"
    const devices = lines
      .map((line: string) => line.trim())
      .filter((line: string) => line.length > 0)
      .map((line: string) => {
        const [id, ...rest] = line.split(' ');
        const modelMatch = rest.join(' ').match(/model:(\S+)/);
        return {
          id,
          model: modelMatch ? modelMatch[1] : '未知设备',
          status: 'online'
        };
      });

    return devices;
  } catch (error) {
    console.error('执行ADB命令出错:', error);
    return [];
  }
}

// 添加测试API，确认preload脚本是否正常加载
const api = {
  test: async () => {
    console.log('preload脚本已加载');
    return ipcRenderer.invoke('test');
  },
  scanDevices: async () => {
    console.log('调用scanDevices...');
    try {
      const devices = await ipcRenderer.invoke('scanDevices');
      console.log('获取到设备列表:', devices);
      return devices;
    } catch (error) {
      console.error('扫描设备失败:', error);
      return [];
    }
  },
  // 文件操作相关API
  openFile: async () => {
    return ipcRenderer.invoke('dialog:openFile');
  },
  saveFile: async (content: string) => {
    return ipcRenderer.invoke('dialog:saveFile', content);
  },
  saveFileAs: async (content: string) => {
    return ipcRenderer.invoke('dialog:saveFileAs', content);
  },
  // 文件传输API
  sendFileToDevice: async (deviceId: string, sourcePath: string, targetPath: string) => {
    return ipcRenderer.invoke('adb:sendFile', deviceId, sourcePath, targetPath);
  }
};

// 使用contextBridge暴露API
contextBridge.exposeInMainWorld('electronAPI', api);

// 文件传输相关IPC
contextBridge.exposeInMainWorld('ipcApi', {
  // 扫描设备
  scanDevices: () => {
    return ipcRenderer.invoke('scan-devices');
  },
  
  // 发送文件到设备
  sendFile: (request: FileTransferRequest) => {
    return ipcRenderer.invoke('send-file', request);
  },
  
  // 监听文件传输进度
  onFileTransferProgress: (callback: (progress: FileTransferProgress) => void) => {
    const listener = (_event: IpcRendererEvent, progress: FileTransferProgress) => {
      callback(progress);
    };
    ipcRenderer.on('file-transfer-progress', listener);
    return () => {
      ipcRenderer.removeListener('file-transfer-progress', listener);
    };
  },

  // 执行脚本
  executeScript: (request: ScriptExecutionRequest) => {
    return ipcRenderer.invoke('execute-script', request);
  },

  // 监听设备连接
  onDeviceConnected: (callback: (event: DeviceConnectionEvent) => void) => {
    const listener = (_event: IpcRendererEvent, deviceInfo: DeviceConnectionEvent) => {
      callback(deviceInfo);
    };
    ipcRenderer.on('device-connected', listener);
    return () => {
      ipcRenderer.removeListener('device-connected', listener);
    };
  },

  // 监听设备断开
  onDeviceDisconnected: (callback: (event: DeviceDisconnectionEvent) => void) => {
    const listener = (_event: IpcRendererEvent, deviceInfo: DeviceDisconnectionEvent) => {
      callback(deviceInfo);
    };
    ipcRenderer.on('device-disconnected', listener);
    return () => {
      ipcRenderer.removeListener('device-disconnected', listener);
    };
  },

  // 监听WebSocket服务器启动
  onWebSocketServerStarted: (callback: (event: WebSocketServerEvent) => void) => {
    const listener = (_event: IpcRendererEvent, serverInfo: WebSocketServerEvent) => {
      callback(serverInfo);
    };
    ipcRenderer.on('ws-server-started', listener);
    return () => {
      ipcRenderer.removeListener('ws-server-started', listener);
    };
  },

  // 监听脚本执行结果
  onScriptResult: (callback: (result: ScriptResult) => void) => {
    const listener = (_event: IpcRendererEvent, result: ScriptResult) => {
      callback(result);
    };
    ipcRenderer.on('script-result', listener);
    return () => {
      ipcRenderer.removeListener('script-result', listener);
    };
  },

  onWsServerStarted: (callback: (event: any, data: { port: number }) => void) => {
    ipcRenderer.on('ws-server-started', callback);
  },
  getWsServerStatus: () => {
    ipcRenderer.send('get-ws-server-status');
  },
  startWsServer: (port: number) => {
    ipcRenderer.send('start-ws-server', { port });
  },
  stopWsServer: () => {
    ipcRenderer.send('stop-ws-server');
  },
  removeAllListeners: (channel: string) => {
    ipcRenderer.removeAllListeners(channel);
  }
}); 